package com.qianli.cashmama.trade.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.api.ApiResponse;
import com.fqgj.common.api.Response;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.msg.ro.SingleSmsSendRequestRO;
import com.fqgj.msg.sms.SmsMsgService;
import com.qianli.cashmama.trade.application.contract.ContractService;
import com.qianli.cashmama.trade.client.bill.BillApplicationService;
import com.qianli.cashmama.trade.client.bill.request.BillPayRequest;
import com.qianli.cashmama.trade.client.trade.TradeApplicationService;
import com.qianli.cashmama.trade.client.trade.request.*;
import com.qianli.cashmama.trade.client.vo.DiscountListVO;
import com.qianli.cashmama.trade.common.enums.AuditResultTypeEnum;
import com.qianli.cashmama.trade.common.enums.TradeClientTypeEnum;
import com.qianli.cashmama.trade.common.enums.TradeTypeEnum;
import com.qianli.cashmama.trade.common.enums.UsageOfLoanEnum;
import com.qianli.cashmama.trade.common.enums.message.MessageSceneEnum;
import com.qianli.cashmama.trade.common.utils.TradeConfigUtil;
import com.qianli.cashmama.trade.dao.TTradeContractDao;
import com.qianli.cashmama.trade.entity.TTradeContractEntity;
import com.qianli.cashmama.trade.integration.notification.message.MessageIntegrationService;
import com.qianli.cashmama.trade.integration.notification.message.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author: moss
 * 2018/10/17
 */
@RequestMapping("/test/185f6751-75a9-4330-8ce8-d9e6ee977aa4")
@Controller
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @Autowired
    TradeApplicationService tradeApplicationService;

    @Autowired
    private TradeConfigUtil configUtil;

    @Autowired
    private MessageUtils messageUtils;

    @Autowired
    private BillApplicationService billApplicationService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private TTradeContractDao tTradeContractDao;

    @Autowired
    private MessageIntegrationService messageIntegrationService;

    //@MotanReferer(basicReferer = "basicRefererConfig", group = "motan_cashmama_message", retries = 1)
    @Autowired
    private SmsMsgService smsMsgService;

    @GetMapping("/signMock/{tradeNo}/{fundCode}")
    @ResponseBody
    public Response signMock(@PathVariable String tradeNo, @PathVariable Integer fundCode) {
        SignCallbackRequest signCallbackRequest = new SignCallbackRequest();
        signCallbackRequest.setTradeNo(tradeNo);
        signCallbackRequest.setContractUrl("https://cashmama-oss-pro.cashmama.in/app/5cbc6b97bc4f475282e0a5277ed231e5.pdf");
        signCallbackRequest.setSignSuccess(true);
        signCallbackRequest.setDocumentId("10000111");
        signCallbackRequest.setSignDate(new Date());
        signCallbackRequest.setCapitalCode(fundCode);
        return tradeApplicationService.signCallback(signCallbackRequest);
    }

    @RequestMapping("/createTrade")
    @ResponseBody
    public String testCreateTeade() {
        CreateTradeRequest tradeRequest = new CreateTradeRequest();
        tradeRequest.setUserCode("2020011099008135003311");
        tradeRequest.setProductCode("dhanadhanv7_3000_7");
        tradeRequest.setChannelCode("test");
        tradeRequest.setClientType(TradeClientTypeEnum.ANDROID);
        tradeRequest.setProductCategory("dhanaDhanV7All");
        tradeRequest.setTradeType(TradeTypeEnum.INNER);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ip", "127.0.0.1");
        tradeRequest.setExtraData(jsonObject.toJSONString());
        TradeExtraData tradeExtraData = new TradeExtraData()
                .setAppCode("38")
                .setIp("127.0.0.1")
                .setVersion("test01")
                .setVersionCode("test01")
                .setPackageName("in.dhanadhan.loan.money.cash");
        tradeRequest.setTradeExtraData(tradeExtraData);
        List<DiscountListVO> discountList = new ArrayList<>();
        tradeRequest.setDiscountList(discountList);
        tradeRequest.setUsageOfLoan(UsageOfLoanEnum.getByCode(0));
        Response response = tradeApplicationService.createTrade(tradeRequest);
        return "ok";

    }

    @RequestMapping("/auditCallBackTest/{tradeNo}/{resultType}")
    @ResponseBody
    public ApiResponse auditCallbackTest(@PathVariable String tradeNo, @PathVariable String resultType) {
        AuditResultTypeEnum auditResultTypeEnum = AuditResultTypeEnum.getEnum(resultType);
        if (auditResultTypeEnum == null) {
            throw new ApplicationException("参数错误");
        }
        AuditResultRequest auditResultRequest = new AuditResultRequest();
        auditResultRequest.setTradeNo(tradeNo);
        auditResultRequest.setResultType(auditResultTypeEnum.getType());
        Response response = tradeApplicationService.auditCallbackV2(auditResultRequest);
        LOGGER.info("response:{}", JSON.toJSONString(response));
        return new ApiResponse();
    }

    @RequestMapping("/payCallBackTest/{tradeNo}")
    @ResponseBody
    public String payCallBackTest(@PathVariable String tradeNo) {
        PayResultRequest payResultRequest = new PayResultRequest(true, new Date())
                .setTradeNo(tradeNo)
                .setResultCode("--");
        payResultRequest.setPayBizNo("paybiztest000003");
        payResultRequest.setCapitalCode(999);
        tradeApplicationService.payCallBackV2(payResultRequest);
        return "pc-OK";
    }

    @RequestMapping("/payCallBackFailedTest/{tradeNo}")
    @ResponseBody
    public String payCallBackFailedTest(@PathVariable String tradeNo) {
        PayResultRequest payResultRequest = new PayResultRequest(false, new Date())
                .setTradeNo(tradeNo)
                .setResultCode("--");
        payResultRequest.setPayBizNo("paybiztest000003");
        payResultRequest.setCapitalCode(999);
        payResultRequest.setPayRetry(true);
        tradeApplicationService.payCallBackV2(payResultRequest);
        return "pf-OK";
    }
//
//    @RequestMapping("/testSMS")
//    @ResponseBody
//    public ApiResponse testSMS() {
//        if (configUtil.isServerTest()) {
//            LOGGER.info("测试发短信");
//            try {
//                Map<String, String> params = new HashMap<>();
//                params.put("name", " " + "张三");
//                SingleSmsSendRequestRO singleSmsSendRequestRO = new SingleSmsSendRequestRO();
//                String messageBizCode = messageUtils.getMessageBizCodeByPackageName("2019010299006567032311", null, MessageSceneEnum.SMS_SIGN_REMIND);
//                singleSmsSendRequestRO.setBizCode(messageBizCode);
//                singleSmsSendRequestRO.setPhone("15899990000");
//                singleSmsSendRequestRO.setReplaceParam(params);
//                singleSmsSendRequestRO.setUserCode("2019010299006567032311");
//                smsMsgService.send(singleSmsSendRequestRO).getData();
//            } catch (Exception e) {
//                LOGGER.info("Signing timeout order closing notifies user of failure,tradeNo:{}", "111", e);
//            }
//            messageIntegrationService.loanNoteByEmail("2019010299006567032311", null, "123123", "test");
//        }
//        return new ApiResponse();
//    }

    @RequestMapping("/getMessageBizCode")
    @ResponseBody
    public Response testMessageBizCode(@RequestBody JSONObject jsonObject) {
        String userCode = jsonObject.getString("userCode");
        String tradeNo = jsonObject.getString("tradeNo");
        String messageBizCode = messageUtils.getMessageBizCodeByPackageName(userCode, tradeNo, MessageSceneEnum.SMS_REPAYMENT_REMINDER);
        JSONObject j1 = new JSONObject();
        j1.put("messageBizCode", messageBizCode);
        return Response.ok(j1);
    }

//    @RequestMapping("/test07")
//    @ResponseBody
//    public String repaymentCallBackV2(@RequestBody JSONObject request) {
//        if (configUtil.isServerTest()) {
//            BillPayRequest billPayRequest = JSON.parseObject(request.toJSONString(), BillPayRequest.class);
//            Response response = billApplicationService.repaymentCallBackV2(billPayRequest);
//            System.out.println(JSON.toJSONString(response));
//        }
//        return "test07,ok";
//    }

    @RequestMapping("/createContract")
    @ResponseBody
    public String createContract(String tradeNo) {
        String contractUrl = contractService.createContract(tradeNo);

        TTradeContractEntity tTradeContractEntity = new TTradeContractEntity();
        tTradeContractEntity.setTradeNo(tradeNo);
        tTradeContractEntity.setContractUrl(contractUrl);
        //tTradeContractEntity.setSignDate(new Date());
        //tTradeContractEntity.setVid(signCallbackRequest.getVid());
        //tTradeContractEntity.setDocumentId(signCallbackRequest.getDocumentId());
        tTradeContractDao.updateByTradeNo(tTradeContractEntity);
        return contractUrl;
    }

    @RequestMapping("/msgtest/{type}")
    public String auditCallbackTest(@PathVariable Integer type) {
        String tradeNo = "191029TT0200450500";
        String userCode = "2019102999008011000400";
        String mobile = "9000011111";
        String name = "zhangsan";
        String borrowCapital = new BigDecimal(5000).toString();
        if (type == 1) {
            messageIntegrationService.sendMessageAfterAuditPass(tradeNo, userCode, mobile, name, borrowCapital);
        }
        if (type == 2) {
            messageIntegrationService.sendMessageAfterAuditRefuse(tradeNo, userCode, mobile, name, borrowCapital);
        }
        if (type == 3) {
            messageIntegrationService.sendMessageAfterNeedHighmark(tradeNo, userCode, mobile, name, borrowCapital);
        }
        return "";
    }

//    @RequestMapping("/rebindCard")
//    @ResponseBody
//    public String updateBankInfoAndLoan(@RequestBody RepayTradeRequest repayTradeRequest) {
//        if (configUtil.isServerTest()) {
//            tradeApplicationService.updateBankInfoAndLoan(repayTradeRequest);
//        }
//        return "rebindCard-ok";
//    }

}
